/** @jsxRuntime classic */
/** @jsx jsx */
import { css, jsx } from '@emotion/react';
import React from 'react';
import Player from './Player';
import Poker from './Poker';
import ReactDOM from 'react-dom'
import { FaBeer } from 'react-icons/fa';
import { BsFillSuitSpadeFill,BsFillSuitClubFill,BsFillDiamondFill,BsFillHeartFill} from "react-icons/bs";
// 声明cache变量，便于匹配是否有循环引用的情况
function myJson(o) {
  var cache = [];
  var str = JSON.stringify(o, function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (cache.indexOf(value) !== -1) {
        // 移除
        return;
      }
      // 收集所有的值
      cache.push(value);
    }
    return value;
  });
  return str;
}

let last = null;
export function PokerOne(props) {
  console.log("PokerOne=======");
  console.log(props);
  let cls = props.className;
  cls =
    cls +
    (props.item.number === 16 ? ' s ' : ' ') +
    (props.item.number === 17 ? 'x' : ' ');
  console.log(props);
  return (
    <div className={cls} 
    onMouseEnter={(e)=>{
      console.log("onMouseEnter");
      if(props.onMouseEnter) props.onMouseEnter(e);
    }}  
    onMouseDown={(e)=>{
      console.log("onMouseDown");
      if(props.onMouseDown) props.onMouseDown(e);
    }} style={{ marginLeft: '-10px' }}>
      {props.item.number < 16 ? (
        <span>
          {props.item.text}
          <Icon item={props.item} />
        </span>
      ) : null}
    </div>
  );
}
function Icon(props) {
  switch (props.item.type) {
    case 0:
      return <BsFillHeartFill className="heart"/>;
    case 1:
      return <BsFillDiamondFill className="heart"/>;
    case 2:
      return <BsFillSuitSpadeFill className="heart2"/>;
    case 3:
      return <BsFillSuitClubFill className="heart2" />;
  }
}
//fa-diamond
//fa-cube
//fa-heartbeat
const css_g = css`
  width: 100vw;
  height: 100vh;
  background-image: url('./img/scene.jpg');
  position: relative;
  .heart {
    color:rgb(255 0 0);
    font-size: 16px;
  }
  .heart2 {
    color:rgb(0 0 0);
    font-size: 16px;
  }
  .pokerDesk {
    height: 80px;
    width: 50px;
    border: solid 1px;
    float: left;
    font-size: 30px;
    background-color: azure;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .pokerDizhu {
    height: 80px;
    width: 50px;
    border: solid 1px;
    border-radius: 8px;
    float: left;
    margin-left: -25px;
    font-size: 20px;
    background-color: azure;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .poker:hover {
    background-color: antiquewhite;
  }

  .selected {
    margin-top: -20px;
  }

  .s {
    background-image: url('./img/s.jpg');
  }

  .x {
    background-image: url('./img/x.png');
  }
`;
function Player2(props) {
  let status = null;
  switch (props.game.stage) {
    case 'ready':
      status = (
        <div
          style={{ display: props.game.stage === 'ready' ? 'block' : 'none' }}
        >
          {props.game.playerList[props.num].ready ? '已准备' : '未准备'}
        </div>
      );
      break;
    case 'jiaoFen':
      status = (
        <div>
          <span>
            {props.game.playerList[props.num].jiaoFen != 0
              ? props.game.playerList[props.num].jiaoFen + '分'
              : '不叫'}
          </span>
        </div>
      );
      break;
    case 'play':
      status = (
        <div>
          <p>剩余 {props.game.playerList[props.num].pokerList.length} 张</p>
            <div>
              {props.game.playerList[props.num].lastSendObj &&
              props.game.playerList[props.num].lastSendObj.poker[0].text ? (
                <div style={{ paddingLeft: '10px' }}>
                  {props.game.playerList[props.num].lastSendObj.poker.map(
                    (item, idx) => {
                      return (
                        <PokerOne key={idx} item={item} className="pokerDizhu" />
                      );
                    }
                  )}
                </div>
              ) : null}
            </div>
        </div>
      );
      break;
  }
  return (
    <div
      style={{
        ...props.style,
        position: 'fixed',
        height: '290px',
        width: '360px',
        top: '100px',
        backgroundColor: 'azure',
        border:
          props.game.currentPlayer === props.game.playerList[props.num]
            ? 'solid 3px red'
            : 'solid 3px green',
      }}
    >
      <p style={{ display: props.game.stage === 'play' ? 'inline' : 'none' }}>
        {props.game.playerList[props.num].type === 'nongmin' ? '农民' : '地主'}
      </p>
      <p>{props.game.playerList[props.num].name}</p>
      <p>
        金币: <span>{props.game.playerList[props.num].money}</span>
      </p>
      {status}
    </div>
  );
}
function getLastNotPass(game){
    let top=game.deskPokerObj;
    if(top && top.type==="pass"){
        return getFromOld(game)
    }
    return top
}
function getFromOld(game){
    if(game.oldPokerList.length<1) return null;
    let at=game.oldPokerList.length-1
    let find=false
    while(at>=0){
        if(game.oldPokerList[at].type=="pass"){

        }
        else{
            find=true;
            return game.oldPokerList[at];
        }
        at -=1;
    }
    return null;
}
function PlayerMe(props) {
  const checkpass=()=>{
    let top=getLastNotPass(props.game)
    
    if(top===null || top.player.index===0){
        return false;
    }
    else{
        return true;
    }

  }
  let lastPai =
    props.game.playerList[props.num].lastSendObj &&
    props.game.playerList[props.num].lastSendObj.poker[0].text ? (
      <div style={{ paddingLeft: '10px' }}>
        {props.game.playerList[props.num].lastSendObj.poker.map((item, idx) => {
          return <PokerOne key={idx} item={item} className="pokerDizhu" />;
        })}
      </div>
    ) : null;
  let chupai =
    <div>
      <div
        style={{
          display:
            (!props.game.checkGameOver() && (props.game.currentPlayer === props.game.playerList[0]))
              ? 'block'
              : 'none',
        }}
      >
        <button style={{width:100,height:60,display:checkpass()?"inline":"none"}} variant="outlined" onClick={props.game.pass}>
          不出
        </button>
        <button style={{width:100,height:60}}  variant="outlined" onClick={props.game.sendPoker2}>
          出牌
        </button>
      </div>
      {lastPai}
    </div>

  let status = null;
  switch (props.game.stage) {
    case 'ready':
      status = (
        <div>
          {props.game.playerList[props.num].ready ? (
            <div
              style={{
                color: 'red',
                width: '80px',
                border: 'solid',
                borderRadius: '4px',
                position: 'absolute',
              }}
            >
              已准备
            </div>
          ) : (
            <button
              onClick={() => {
                console.log('hi');
                props.game.setReadyOne();
              }}
              style={{
                fontSize: '40px',
                height: '60px',
                lineHeight: '30px',
                borderRadius: '4px',
                backgroundColor: 'pink',
              }}
            >
              准备
            </button>
          )}
        </div>
      );
      break;
    case 'jiaoFen':
      let status0;
      if (props.game.currentJiaoFenPlayer === props.game.playerList[0]) {
        status0 = (
          <div>
            <button style={{width:100,height:60}} 
              onClick={() => {
                props.game.playerList[0].setJiaoFen(0);
              }}
            >
              不叫
            </button>
            <button style={{width:100,height:60}} 
              onClick={() => {
                props.game.playerList[0].setJiaoFen(1);
              }}
            >
              1分
            </button>
            <button style={{width:100,height:60}} 
              onClick={() => {
                props.game.playerList[0].setJiaoFen(2);
              }}
            >
              2分
            </button>
            <button style={{width:100,height:60}} 
              onClick={() => {
                props.game.playerList[0].setJiaoFen(3);
              }}
            >
              3分
            </button>
          </div>
        );
      } else {
        status0 = (
          <div>
            <span>{props.game.playerList[0].jiaoFen}分</span>
          </div>
        );
      }
      status = (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ marginLeft: '10px' }}>
            {props.game.playerList[0].pokerList.map((item, idx) => {
              return (
                <PokerOne className={
                    'poker pokerDizhu ' +
                    (item.selected ? 'selected ' : ' ')
                  }
                  item={item}
                  key={idx}
                />
              );
              // return (
              //   <div
              //     style={{ marginLeft: '-10px', borderRadius: '8px' }}
              //     key={idx}
              //     onMouseEnter={(e) => {
              //       props.game.enter(e, item);
              //     }}
              //     onMouseDown={() => {
              //       props.game.pickPoker(item);
              //     }}
              //     className={
              //       'poker pokerDesk ' +
              //       (item.selected ? 'selected ' : ' ') +
              //       (item.number === 16 ? 's ' : ' ') +
              //       (item.number === 17 ? 'x' : ' ')
              //     }
              //   >
              //     {item.number < 16 ? <span>{item.text}</span> : null}
              //   </div>
              // );
            })}
          </div>
          {status0}
        </div>
      );
      break;
    case 'play':
      status = (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <div style={{ marginLeft: '10px' ,border:"solid blue 1px"}}>
            {props.game.playerList[0].pokerList.map((item, idx) => {
              return (
                <PokerOne className={
                    'poker pokerDizhu ' +
                    (item.selected ? 'selected ' : ' ')
                  }
                  item={item}
                  key={idx}
                  onMouseEnter={(e) => {
                    props.game.enter(e, item);
                  }}
                  onMouseDown={() => {
                    props.game.pickPoker(item);
                  }}
                />
                // <div
                //   style={{ marginLeft: '-10px', borderRadius: '8px' }}
                //   key={idx}
                //   onMouseEnter={(e) => {
                //     props.game.enter(e, item);
                //   }}
                //   onMouseDown={() => {
                //     props.game.pickPoker(item);
                //   }}
                //   className={
                //     'poker pokerDesk ' +
                //     (item.selected ? 'selected ' : ' ') +
                //     (item.number === 16 ? 's ' : ' ') +
                //     (item.number === 17 ? 'x' : ' ')
                //   }
                // >
                //   {item.number < 16 ? <span>{item.text}</span> : null}
                // </div>
              );
            })}
          </div>
          <div>{chupai}</div>
        </div>
      );
      break;
  }
  return (
    <div
      style={{
        ...props.style,
        position: 'fixed',
        height: '350px',
        width: '100%',
        top: '400px',
        backgroundColor: 'azure',
        border:
          props.game.currentPlayer === props.game.playerList[props.num]
            ? 'solid 4px red'
            : 'solid 4px green',
      }}
    >
      <p style={{ display: props.game.stage === 'play' ? 'inline' : 'none' }}>
        {props.game.playerList[props.num].type === 'nongmin' ? '农民' : '地主'}
      </p>
      <p>{props.game.playerList[props.num].name}</p>
      <p>
        金币: <span>{props.game.playerList[props.num].money}</span>
      </p>
      {status}
    </div>
  );
}

export default class Game extends React.Component {
  constructor(props) {
    super(props);
    this.testModel = false; //测试模式 三个AI自动打牌
    this.playerList = [];
    this.pokerList = [];
    this.dizhuPokerList = [];
    this.deskPokerObj = null;
    this.oldPokerList = [];
    this.currentPlayer = null;
    this.currentJiaoFenPlayer = null;
    this.jiaoFenCount = 0;
    this.dizhu = null;
    this.MaxSecond = 60;
    this.second = this.MaxSecond;
    this.BaseScore = 1; //每局底分
    this.score = this.BaseScore; //当前局分
    this.stage = 'ready'; //阶段 ready\jiaoFen\play
    this.loop = null;
    this.jiaofen = [];
    this.init();
  }

  init() {
    this.initPokerList();
    this.initPlayerList();
  }
  setReady() {
    // console.log("hereeretre")
    if (
      this.playerList[0] &&
      this.playerList[0].ready &&
      this.playerList[1] &&
      this.playerList[1].ready &&
      this.playerList[2] &&
      this.playerList[2].ready
    ) {
      console.log('sendPoker');
      this.sendPoker();
      this.startJiaoFen();
      this.refresh();
    }
  }
  refresh = () => {
    console.log('refresh');
    this.forceUpdate();
    // if (last===null){
    //   last=myJson(this)
    //   this.forceUpdate();
    // }
    // else{
    //   let cur=myJson(this)
    //   if(last===cur){
    //     console.log("not need forceUpdate");
    //   }
    //   else{
    //     last=cur;
    //     console.log(last);
    //     this.forceUpdate();
    //   }
    // }
  };
  //开始叫分
  startJiaoFen() {
    this.stage = 'jiaoFen';
    let index = this.getRandomIntInclusive(0, 2);
    this.currentJiaoFenPlayer = this.playerList[index];
  }

  someOneJiaoFen(fen) {
    this.jiaofen.push(fen);
    console.log(this.jiaofen);
    let num = this.jiaofen.length;
    if (num > 2) {
      if (this.jiaofen[num - 1] === 0 && this.jiaofen[num - 2] === 0) {
        this.setDiZhu2(this.currentJiaoFenPlayer.last.last);
      }
    }
    this.jiaoFenCount++;

    // let timeWait = 1000;
    // if(this.testModel){
    //     timeWait = 0;
    // }
    // console.log("timeWait==")
    // console.log(timeWait);
    if (this.jiaoFenCount === 30) {
      this.setDiZhu(this.currentJiaoFenPlayer);
    } else {
      this.currentJiaoFenPlayer = this.currentJiaoFenPlayer.next;
    }
    this.refresh();
  }
  setDiZhu2(who) {
    let dizhu = who;
    dizhu.type = 'dizhu';
    this.dizhu = dizhu;

    this.sendDiZhuPoker();
    this.start();
  }
  setDiZhu() {
    let sortList = this.playerList.slice(0).sort(this.sortByJiaoFen);

    let dizhu;
    if (sortList[0].jiaoFen === sortList[1].jiaoFen) {
      if (sortList[0].jiaoFen === sortList[2].jiaoFen) {
        let index = this.getRandomIntInclusive(0, 2);
        dizhu = sortList[index];
      } else {
        let index = this.getRandomIntInclusive(0, 1);
        dizhu = sortList[index];
      }
    } else {
      dizhu = sortList[0];
    }

    dizhu.type = 'dizhu';
    this.dizhu = dizhu;

    this.sendDiZhuPoker();
    this.start();
  }

  sortByJiaoFen(a, b) {
    return b.jiaoFen - a.jiaoFen;
  }

  resetTime() {
    this.second = this.MaxSecond;
  }

  timeLoop() {
    if (this.stage !== 'play') {
      return;
    }
    this.second--;

    if (this.second === 0) {
      this.timeout();
    }

    setTimeout(() => {
      this.timeLoop();
    }, 1000);
  }

  timeout() {
    this.currentPlayer.playByString('pass');
    this.refresh();
  }

  start() {
    this.stage = 'play';
    this.timeLoop();
    this.currentPlayer = this.dizhu;
    if (this.currentPlayer.isRobot) {
      this.currentPlayer.playByAI();
    }
    this.refresh();
  }

  reset() {
    this.playerList[0].reset();
    this.playerList[1].reset();
    this.playerList[2].reset();

    this.pokerList = [];
    this.dizhuPokerList = [];
    this.deskPokerObj = null;
    this.oldPokerList = [];
    this.currentPlayer = null;
    this.currentJiaoFenPlayer = null;
    this.jiaoFenCount = 0;
    this.dizhu = null;
    this.second = this.MaxSecond;
    this.score = this.BaseScore;
    this.stage = 'ready';
    this.initPokerList();
    this.refresh();
  }

  //有玩家出牌
  someOneSendPoker(obj) {
    console.log("someOneSendPoker")
    this.clearDesk();
    this.deskPokerObj = obj;

    this.checkBoom(obj);

    let over = this.checkGameOver();
    if (over) {
        this.refresh()
        setTimeout(()=>{
          this.gameOver();
          this.refresh();
        },3000)
        return;
    }

    this.next();//refresh
  }

  //炸弹分数翻1番 火箭翻2番
  checkBoom(obj) {
    if (obj.type === 'four') {
      this.score *= 2;
    } else if (obj.type === 'four') {
      this.score *= 4;
    }
  }

  next() {
    this.resetTime();
    this.currentPlayer = this.currentPlayer.next;
    if (this.currentPlayer.isRobot) {
      this.currentPlayer.playByAI();
    }
    this.refresh();
  }

  gameOver() {
    setTimeout(() => {
      if (!this.testModel) {
        console.log(
          '游戏结束! ' +
            this.currentPlayer.name +
            ' [' +
            this.currentPlayer.type +
            '] 胜!'
        );
      } else {
        console.log(
          this.playerList[0].money +
            ' ' +
            this.playerList[1].money +
            ' ' +
            this.playerList[2].money +
            ' '
        );
      }
      this.settleMoney();
      this.reset();
    }, 1000);
  }

  //结算金币得失
  settleMoney() {
    if (this.currentPlayer.type === 'nongmin') {
      this.currentPlayer.money += this.score;

      if (this.currentPlayer.next.type === 'nongmin') {
        this.currentPlayer.next.money += this.score;
      } else {
        this.currentPlayer.next.money -= this.score * 2;
      }

      if (this.currentPlayer.last.type === 'nongmin') {
        this.currentPlayer.last.money += this.score;
      } else {
        this.currentPlayer.last.money -= this.score * 2;
      }
    } else {
      this.currentPlayer.money += this.score * 2;
      this.currentPlayer.next.money -= this.score;
      this.currentPlayer.last.money -= this.score;
    }
    this.refresh();
  }

  checkGameOver=()=> {
    if (this.currentPlayer &&  this.currentPlayer.pokerList.length === 0) {
      return true;
    }
  }

  clearDesk() {
    if (this.deskPokerObj) {
      this.oldPokerList.push(this.deskPokerObj);
      this.deskPokerObj = null;
    }
  }

  sendDiZhuPoker() {
    do {
      let poker = this.pokerList.splice(0, 1)[0];
      this.dizhu.addPoker(poker);
    } while (this.pokerList.length > 0);

    this.dizhu.sortPoker();
  }

  sendPoker() {
    let player = this.playerList[0];
    do {
      let index = this.getRandomIntInclusive(0, this.pokerList.length - 1);
      let poker = this.pokerList.splice(index, 1)[0];
      player.addPoker(poker);
      player = player.next;
    } while (this.pokerList.length > 3);

    for (let i = 0; i < this.playerList.length; i++) {
      this.playerList[i].sortPoker();
    }

    this.dizhuPokerList = this.pokerList.slice(0);
  }

  initPlayerList() {
    let that = this;
    this.playerList = [];
    let player0 = new Player({
      name: 'player',
      isRobot: that.testModel,
      game: this,
    });
    let player1 = new Player({
      name: '机器人1',
      isRobot: true,
      game: this,
    });
    let player2 = new Player({
      name: '机器人2',
      isRobot: true,
      game: this,
    });
    this.playerList = [player0, player1, player2];

    this.playerList[0].next = this.playerList[1];
    this.playerList[0].index=0;
    this.playerList[1].index=1;
    this.playerList[2].index=2;

    this.playerList[1].next = this.playerList[2];
    this.playerList[2].next = this.playerList[0];
    this.playerList[0].last = this.playerList[2];
    this.playerList[1].last = this.playerList[0];
    this.playerList[2].last = this.playerList[1];
  }

  initPokerList() {
    this.pokerList = [];
    for (let number = 3; number <= 15; number++) {
      for (let type = 0; type < 4; type++) {
        let poker = new Poker({
          number: number,
          type: type,
        });
        this.pokerList.push(poker);
      }
    }
    for (let number = 16; number <= 17; number++) {
      let poker = new Poker({
        number: number,
      });
      this.pokerList.push(poker);
    }
  }
  playerMarginLeft = () => {
    return (window.innerWidth - this.playerList[0].pokerList.length * 50) / 2;
  };
  deskPokerMarginLeft = () => {
    return (
      (window.innerWidth - this.playerList[0].lastSendObj.poker.length * 50) / 2
    );
  };
  buttonMarginLeft = () => {
    return (window.innerWidth - 400) / 2;
  };
  playerJiaoFenMargin = () => {
    return window.innerWidth / 2 - 30;
  };
  dizhuPokerMarginLeft = () => {
    return (window.innerWidth - this.dizhuPokerList.length * 50) / 2;
  };

  setReadyOne = function () {
    console.log('setReady');
    this.playerList[0].setReady();
  };

  enter = function (e, poker) {
    if (e.buttons === 1) {
      this.pickPoker(poker);
    }
  };

  pickPoker = (poker) => {
    if (!poker.selected) {
      poker.selected = true;
      this.pokerList.push(poker);
    } else {
      poker.selected = false;
      for (let i = 0; i < this.pokerList.length; i++) {
        if (this.pokerList[i] === poker) {
          this.pokerList.splice(i, 1);
        }
      }
    }
    this.refresh();
  };

  sendPoker2 = () => {
    let success = this.playerList[0].playByPokerList(this.pokerList);
    if (success) {
      this.pokerList = [];
    }
  };

  pass = () => {
    this.playerList[0].playByString('pass');
  };
  getRandomIntInclusive(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  render() {
    //       var data='fuck1';
    // var playerStr="";
    // var pokerList=[];
    console.log('render=========');
    // return (<div css={css_g}>
    //   <PokerOne className="pokerDesk"  item={{text:"2",number:3,type:1}} />
    //   </div>);
    return (
      <div css={css_g}>
        <div
          style={{
            height: '150px',
            backgroundColor: 'azure',
            border: 'solid 1px blue',
            margin: '0 auto',
            width: '200px',
          }}
        >
          <div
            style={{
              paddingLeft: '30px',
              paddingTop: '30px',
              display: this.stage === 'play' ? 'block' : 'none',
            }}
          >
            底牌
            {this.dizhuPokerList.map((item, idx) => {
              return <PokerOne key={idx} className="pokerDizhu" item={item} />;
            })}
          </div>
        </div>

        <Player2 game={this} num={2} style={{ left: '20px' }} />
        <Player2 game={this} num={1} style={{ right: '20px' }} />
        <PlayerMe game={this} num={0} />
      </div>
    );
  }
}

// export default Game;
